<template>
  <div class="data-upload-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-bar">
        <label class="search-module-label">数据上传</label>
        <el-form :model="queryParams" :inline="true" class="search-form">
          <!-- 事件名称 -->
          <el-form-item label="事件名称">
            <el-select
              v-model="queryParams.eventName"
              placeholder="请选择事件名称"
              style="width: 180px"
            >
              <el-option
                label="2024年12月11日汤营超桥"
                value="20241211tycq"
              ></el-option>
              <el-option
                label="2024年12月15日河道治理"
                value="20241215hdzl"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 监测点名称 -->
          <el-form-item label="监测点名称">
            <el-select
              v-model="queryParams.pointName"
              placeholder="请选择监测点"
              style="width: 180px"
            >
              <el-option label="汤营超桥监测点" value="tycqjcdd"></el-option>
              <el-option label="河道上游监测点" value="hdsyjcdd"></el-option>
            </el-select>
          </el-form-item>

          <!-- 监测因子 -->
          <el-form-item label="监测因子">
            <el-input
              v-model="queryParams.monitorFactor"
              placeholder="请输入监测因子"
              style="width: 180px"
              clearable
            />
          </el-form-item>

          <!-- 监测时间 -->
          <el-form-item label="监测时间">
            <el-date-picker
              v-model="queryParams.monitorTime"
              type="datetime"
              placeholder="选择监测时间"
              style="width: 180px"
              clearable
            />
          </el-form-item>

          <!-- 监测值 -->
          <el-form-item label="监测值">
            <el-input-number
              v-model="queryParams.monitorValue"
              placeholder="请输入监测值"
              style="width: 180px"
              clearable
            />
          </el-form-item>

          <!-- 量纲 -->
          <el-form-item label="量纲">
            <el-select
              v-model="queryParams.unit"
              placeholder="请选择量纲"
              style="width: 180px"
            >
              <el-option label="mg/L" value="mg/L"></el-option>
              <el-option label="℃" value="℃"></el-option>
            </el-select>
          </el-form-item>

          <!-- 评价标准 -->
          <el-form-item label="评价标准">
            <el-input
              v-model="queryParams.evalStandard"
              placeholder="请输入评价标准"
              style="width: 180px"
              clearable
            />
          </el-form-item>

          <!-- 搜索/重置按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh-right"
              @click="handleReset"
              style="margin-left: 8px"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 操作区域 + 表格 -->
    <el-card class="table-card">
      <div class="operate-bar">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          @click="handleBatchUpdate"
          :disabled="selectedRows.length !== 1"
          >修改</el-button
        >
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          >删除</el-button
        >
      </div>

      <el-table
        :data="tableList.rows"
        border
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 600 }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column prop="eventName" label="事件名称" align="center" />
        <el-table-column prop="pointName" label="监测点名称" align="center" />
        <el-table-column prop="monitorFactor" label="监测因子" align="center" />
        <el-table-column prop="monitorTime" label="监测时间" align="center" />
        <el-table-column prop="monitorValue" label="监测值" align="center" />
        <el-table-column prop="unit" label="量纲" align="center" />
        <el-table-column prop="evalStandard" label="评价标准" align="center" />
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDetail(scope.row)"
              style="color: #409eff"
              >详情</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.row)"
              style="color: #67c23a"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="handleDel(scope.row)"
              style="color: #f56c6c"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
        style="margin-top: 15px; text-align: right"
      />
    </el-card>

    <!-- 新增/修改弹框（图2样式） -->
    <el-dialog
      :title="formTitle"
      :visible.sync="formDialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*事件名称" prop="eventName">
              <el-select
                v-model="form.eventName"
                placeholder="请选择事件名称"
                style="width: 100%"
              >
                <el-option
                  label="2024年12月11日汤营超桥"
                  value="20241211tycq"
                ></el-option>
                <el-option
                  label="2024年12月15日河道治理"
                  value="20241215hdzl"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*监测点名称" prop="pointName">
              <el-select
                v-model="form.pointName"
                placeholder="请选择监测点"
                style="width: 100%"
              >
                <el-option label="汤营超桥监测点" value="tycqjcdd"></el-option>
                <el-option label="河道上游监测点" value="hdsyjcdd"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*监测值" prop="monitorValue">
              <el-input-number
                v-model="form.monitorValue"
                placeholder="请输入监测值"
                style="width: 100%"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测时间" prop="monitorTime">
              <el-date-picker
                v-model="form.monitorTime"
                type="datetime"
                placeholder="选择监测时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="量纲" prop="unit">
              <el-select
                v-model="form.unit"
                placeholder="请选择量纲"
                style="width: 100%"
              >
                <el-option label="mg/L" value="mg/L"></el-option>
                <el-option label="℃" value="℃"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*监测因子" prop="monitorFactor">
              <el-input
                v-model="form.monitorFactor"
                placeholder="请输入监测因子"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评价标准" prop="evalStandard">
              <el-input
                v-model="form.evalStandard"
                placeholder="请输入评价标准"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入备注"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFormDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹框 -->
    <el-dialog
      title="监测数据详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="detailForm" label-width="100px" class="detail-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件名称">
              <el-input v-model="detailForm.eventName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测点名称">
              <el-input v-model="detailForm.pointName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="监测因子">
              <el-input v-model="detailForm.monitorFactor" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测时间">
              <el-input v-model="detailForm.monitorTime" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="监测值">
              <el-input v-model="detailForm.monitorValue" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="量纲">
              <el-input v-model="detailForm.unit" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评价标准">
              <el-input v-model="detailForm.evalStandard" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                v-model="detailForm.remark"
                readonly
                :placeholder="detailForm.remark ? '' : '无'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "DataUpload", // 组件名称
  components: {},
  data() {
    return {
      // 表格高度（自适应窗口）
      tableHeight: window.innerHeight - 400,
      // 查询参数（匹配图1搜索项）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventName: "",
        pointName: "",
        monitorFactor: "",
        monitorTime: "",
        monitorValue: "",
        unit: "",
        evalStandard: "",
      },
      // 表格数据（匹配图1示例）
      tableList: {
        total: 0,
        rows: [],
      },
      tableData: [
        {
          id: 1,
          eventName: "2024年12月11日汤营超桥",
          pointName: "汤营超桥监测点",
          monitorFactor: "氨氮",
          monitorTime: "2025-01-07 17:05:20",
          monitorValue: 2,
          unit: "mg/L",
          evalStandard: "",
          remark: "",
        },
        {
          id: 2,
          eventName: "2024年12月11日汤营超桥",
          pointName: "汤营超桥监测点",
          monitorFactor: "高锰酸盐指数",
          monitorTime: "2025-01-07 17:05:33",
          monitorValue: 2,
          unit: "mg/L",
          evalStandard: "",
          remark: "",
        },
      ],
      // 选中的表格数据
      selectedRows: [],
      // 新增/修改弹框（图2）
      formDialogVisible: false,
      formTitle: "",
      form: {
        id: "",
        eventName: "",
        pointName: "",
        monitorValue: 0, // 图2默认监测值为0
        monitorTime: "",
        unit: "",
        monitorFactor: "",
        evalStandard: "",
        remark: "",
      },
      // 表单校验规则（图2必填项）
      formRules: {
        eventName: [
          { required: true, message: "请选择事件名称", trigger: "blur" },
        ],
        pointName: [
          { required: true, message: "请选择监测点名称", trigger: "blur" },
        ],
        monitorValue: [
          { required: true, message: "请输入监测值", trigger: "blur" },
        ],
        monitorFactor: [
          { required: true, message: "请输入监测因子", trigger: "blur" },
        ],
      },
      // 详情弹框
      detailDialogVisible: false,
      detailForm: {},
    };
  },
  mounted() {
    this.pageInit();
    // 监听窗口大小变化，调整表格高度
    window.addEventListener("resize", () => {
      this.tableHeight = window.innerHeight - 400;
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", () => {});
  },
  methods: {
    // 页面初始化
    pageInit() {
      this.getList();
    },

    // 获取表格数据（前端模拟，实际替换为接口请求）
    getList() {
      let filteredData = [...this.tableData];
      // 按查询参数筛选
      if (this.queryParams.eventName) {
        filteredData = filteredData.filter(
          (item) => item.eventName === this.queryParams.eventName
        );
      }
      if (this.queryParams.pointName) {
        filteredData = filteredData.filter(
          (item) => item.pointName === this.queryParams.pointName
        );
      }
      if (this.queryParams.monitorFactor) {
        filteredData = filteredData.filter((item) =>
          item.monitorFactor.includes(this.queryParams.monitorFactor)
        );
      }
      if (this.queryParams.monitorTime) {
        filteredData = filteredData.filter((item) =>
          item.monitorTime.includes(this.queryParams.monitorTime)
        );
      }
      if (
        this.queryParams.monitorValue !== "" &&
        this.queryParams.monitorValue !== undefined
      ) {
        filteredData = filteredData.filter(
          (item) => item.monitorValue === this.queryParams.monitorValue
        );
      }
      if (this.queryParams.unit) {
        filteredData = filteredData.filter(
          (item) => item.unit === this.queryParams.unit
        );
      }
      if (this.queryParams.evalStandard) {
        filteredData = filteredData.filter((item) =>
          item.evalStandard.includes(this.queryParams.evalStandard)
        );
      }

      // 分页处理
      this.tableList.total = filteredData.length;
      const startIndex =
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const endIndex = startIndex + this.queryParams.pageSize;
      this.tableList.rows = filteredData.slice(startIndex, endIndex);
    },

    // 表格选中事件
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 搜索查询
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询条件
    handleReset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        eventName: "",
        pointName: "",
        monitorFactor: "",
        monitorTime: "",
        monitorValue: "",
        unit: "",
        evalStandard: "",
      };
      this.getList();
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 新增按钮操作（打开图2弹窗）
    handleAdd() {
      this.resetForm();
      this.formDialogVisible = true;
      this.formTitle = "添加手动监测数据";
    },

    // 批量修改
    handleBatchUpdate() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择一条数据进行修改");
        return;
      }
      if (this.selectedRows.length > 1) {
        this.$message.warning("只能选择一条数据进行修改");
        return;
      }
      this.resetForm();
      this.form = { ...this.selectedRows[0] };
      this.formDialogVisible = true;
      this.formTitle = "修改手动监测数据";
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择需要删除的数据");
        return;
      }
      this.$confirm(
        `确定要删除选中的 ${this.selectedRows.length} 条数据吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          const ids = this.selectedRows.map((item) => item.id);
          this.tableData = this.tableData.filter(
            (item) => !ids.includes(item.id)
          );
          this.getList();
          this.selectedRows = [];
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 查看详情
    handleDetail(row) {
      this.detailForm = { ...row };
      this.detailDialogVisible = true;
    },

    // 单行修改
    handleEdit(row) {
      this.resetForm();
      this.form = { ...row };
      this.formDialogVisible = true;
      this.formTitle = "修改手动监测数据";
    },

    // 单行删除
    handleDel(row) {
      this.$confirm(`确定要删除「${row.monitorFactor}」数据吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData = this.tableData.filter((item) => item.id !== row.id);
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 重置表单
    resetForm() {
      this.form = {
        id: "",
        eventName: "",
        pointName: "",
        monitorValue: 0,
        monitorTime: "",
        unit: "",
        monitorFactor: "",
        evalStandard: "",
        remark: "",
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    // 关闭弹框
    closeFormDialog() {
      this.formDialogVisible = false;
      this.resetForm();
    },

    // 提交表单（新增/修改）
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 校验唯一性（事件+监测点+监测因子）
          if (!this.form.id) {
            const isDuplicate = this.tableData.some(
              (item) =>
                item.eventName === this.form.eventName &&
                item.pointName === this.form.pointName &&
                item.monitorFactor === this.form.monitorFactor
            );
            if (isDuplicate) {
              this.$message.error("该事件下该监测点的此监测因子已存在数据");
              return;
            }
          }

          // 修改/新增逻辑
          if (this.form.id) {
            const index = this.tableData.findIndex(
              (item) => item.id === this.form.id
            );
            this.tableData.splice(index, 1, { ...this.form });
            this.$message.success("修改成功");
          } else {
            this.form.id = new Date().getTime();
            this.tableData.unshift({ ...this.form });
            this.$message.success("新增成功");
          }
          this.formDialogVisible = false;
          this.getList();
          this.resetForm();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.data-upload-container {
  padding: 15px;
  background-color: #f9f9f9;
  min-height: calc(100vh - 20px);

  // 搜索卡片
  .search-card {
    margin-bottom: 15px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

    .search-bar {
      display: flex;
      align-items: center;
      padding: 10px 0;

      .search-module-label {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-right: 20px;
      }

      .search-form {
        flex: 1;

        .el-form-item {
          margin-right: 15px;
          margin-bottom: 0;
        }

        .el-form-item__label {
          color: #666;
          font-weight: 500;
        }
      }
    }
  }

  // 表格卡片
  .table-card {
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

    .operate-bar {
      margin-bottom: 12px;
      padding-left: 5px;

      .el-button {
        margin-right: 10px;
      }
    }

    .el-table {
      border-radius: 4px;
      overflow: hidden;

      .el-table__row:hover {
        background-color: #fafafa;
      }

      .cell {
        white-space: nowrap;
      }
    }
  }

  // 表单弹框
  .form-container {
    .el-form-item {
      margin-bottom: 18px;
    }

    .el-form-item__label {
      color: #333;
      font-weight: 500;
      &::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
      &.el-form-item__label--no-asterisk::before {
        content: "";
        margin-right: 0;
      }
    }

    .el-input-number {
      width: 100%;
    }
  }

  // 详情弹框
  .detail-form {
    .el-form-item {
      margin-bottom: 18px;
    }

    .el-form-item__label {
      color: #333;
      font-weight: 500;
    }

    .el-input[readonly] {
      background-color: #f9f9f9;
      color: #666;
      cursor: not-allowed;
    }
  }

  // 弹框底部
  .dialog-footer {
    text-align: right;
    margin-top: 10px;
  }

  // 响应式适配
  @media (max-width: 1200px) {
    .search-bar {
      flex-direction: column;
      align-items: flex-start !important;

      .search-module-label {
        margin-bottom: 10px;
      }

      .search-form .el-form-item {
        margin-bottom: 10px;
      }
    }
  }

  @media (max-width: 992px) {
    .tableHeight {
      height: auto !important;
    }

    .form-container .el-row,
    .detail-form .el-row {
      flex-direction: column;
    }

    .form-container .el-col,
    .detail-form .el-col {
      width: 100% !important;
      margin-bottom: 8px;
    }
  }
}
</style>
